"""
Grave! Important! Важно!

Proletoj el ĉiuj landoj, unuiĝu!
Workers of the world, unite!
Пролетарии всех стран, соединяйтесь!

https://tkom.pro
"""

from rest_framework import serializers
from main.models import Uzanto
from urllib.parse import urljoin
from django.conf import settings


class AbsoluteURLMixin:
    def _media_url(self, relative_url):
        return self.context.get('request').build_absolute_uri(urljoin(settings.MEDIA_URL, relative_url))

    def _object_url(self, relative_url):
        return self.context.get('request').build_absolute_uri(relative_url)


class UzantoSerializer(serializers.HyperlinkedModelSerializer, AbsoluteURLMixin):
    chefa_lingvo = serializers.StringRelatedField()
    unua_nomo = serializers.StringRelatedField()
    dua_nomo = serializers.StringRelatedField()
    familinomo = serializers.StringRelatedField()
    url = serializers.SerializerMethodField(read_only=True)
    avataro_bildo = serializers.SerializerMethodField()
    detail = serializers.HyperlinkedIdentityField(view_name='api:uzantoj-detail')

    class Meta:
        model = Uzanto
        fields = ('id', 'unua_nomo', 'dua_nomo', 'familinomo', 'chefa_lingvo', 'avataro_bildo', 'detail', 'url')

    def get_url(self, obj):
        return self._object_url(obj.get_absolute_url())

    def get_avataro_bildo(self, obj):
        return self._media_url(obj.avataro_bildo)